/*
 * Public Credit Information Sharing Platform(PCISP).
 * Copyright (c) 2019-2020 jsxzkingdee and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * Please visit https://www.zhengxinsoft.com if you need additional information or have any questions.
 */

package com.platform.core.web.controller;
import com.google.common.collect.Maps;
import com.platform.comm.exceptions.RestApiException;
import com.platform.comm.util.RestUtil;
import com.platform.comm.entity.CommDataInfoEntity;
import com.platform.comm.service.ICommDataInfoBiz;
import com.platform.comm.web.results.DataJsonResult;
import com.platform.comm.web.results.JsonResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Description: com.platform.core.web.controller
 *
 * @author zhangqian
 */
@RestController
@RequestMapping(name = "通用上传下载", path = "/management/comm/file")
public class CommFileController {

    private final ICommDataInfoBiz commDataInfoBiz;

    public CommFileController(ICommDataInfoBiz commDataInfoBiz) {
        this.commDataInfoBiz = commDataInfoBiz;
    }

    /**
     * 文件上传
     */
    @PostMapping(name = "上传文件", path = "/upload")
    public JsonResult create(@RequestParam MultipartFile[] attachments) {
        List<Map<String, String>> fileList = com.google.common.collect.Lists.newArrayList();
        // 存储附件信息
        Arrays.stream(attachments).forEach(attach -> {
            Map<String, String> paramsMap = Maps.newHashMap();
            CommDataInfoEntity commDataInfoEntity = commDataInfoBiz.saveRecord(paramsMap, attach);
            Map<String, String> fileMap = Maps.newHashMap();
            fileMap.put("id", commDataInfoEntity.getId());
            fileMap.put("fileName", commDataInfoEntity.getFileName());
            fileList.add(fileMap);
        });
        return DataJsonResult.succeed(fileList);
    }

    @PostMapping(name = "下载内容附件(无需登录)", path = "/downLoad")
    public void downLoad(@RequestBody Map<String,String> map,HttpServletResponse response) throws IOException {
        CommDataInfoEntity commDataInfoEntity = commDataInfoBiz.queryCommDataImpById(map.get("attachmentId"));
        if (Objects.isNull(commDataInfoEntity)){
            throw new RestApiException("您要下载的文件不存在！");
        }
        InputStream inputStream = commDataInfoBiz.downLoadFile(commDataInfoEntity.getId());
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + commDataInfoEntity.getFileName());
        RestUtil.copy(inputStream, response.getOutputStream());
    }

}
